package com.wavehi.homework.fifth;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.text.Collator;
import java.util.Arrays;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author WaveHi
 * @Date 28/8/2021 下午 8:22
 * @Version 1.0
 * @Contact HJBWaveHi@163.com
 * @Description Fifth homework : Demonstrate the use of Collectors
 */
public class CollectorsDemo1 {

    public static void main(String[] args) {
        //获取数据源
        File srcFile = new File("day16_new_feature/others/charsfile.txt");
        BufferedReader bufferedReader = null;
        StringBuilder sb = null;
        try {
            //获取输入流
            FileReader fileReader = new FileReader(srcFile);
            bufferedReader = new BufferedReader(fileReader);
            //接收数据
            sb = new StringBuilder(16);
            //接收每次读取的数据
            int data = ' ';
            //读取数据
            while((data = bufferedReader.read()) != -1) {
                sb.append((char)data);
                sb.append(' ');
            }
            System.out.println("Data transfer completed!");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //资源的关闭
            if(bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        //利用流对数据进行处理
        System.out.println(Arrays.stream(new String(sb).trim().split(" "))
                .filter(s -> s.matches("[a-z|A-Z]"))
                .collect(Collectors.groupingBy(a -> a, TreeMap<String, Long>::new, Collectors.counting()))
                .entrySet().stream().map(stringLongEntry -> {
                    if(!"{".equals(stringLongEntry.getKey())){
                        return stringLongEntry.getKey() + "(" + stringLongEntry.getValue() + ")";
                    }
                    return "";
                })
                .collect(Collectors.joining(",")));
    }

}

/*小结：counting() 统计接收到的数据。
       joining(CharSet cs) 将流的数据以指定的连接符连接为一个字符串
 */